import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/network_image_load/load_image.dart';
import 'package:yt_devops/model/picture_upload_setting.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/common/common_services.dart';
import 'package:yt_devops/styles/styles.dart';

class UserAvatarWidget extends StatelessWidget {
  final String avatarUrl;
  final Function(String) imageUrlCallBack;
  final String holderImg;
  final bool isRequired; //是否为必填.如果是则前面加红色*号
  final bool isCanClick; //是否能点击上传头像,如果是查看则不可点击
  final bool isShowRightArrow; //是否显示右侧箭头
  const UserAvatarWidget(this.avatarUrl, this.imageUrlCallBack,
      {this.holderImg = 'assets/images/mine_user_detail_default_avator',
      this.isRequired = false,
      this.isCanClick = true,
      this.isShowRightArrow = true,
      super.key});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 75,
      child: Row(
        children: [
          isRequired
              ? Container(
                  alignment: Alignment.center,
                  margin: const EdgeInsets.only(left: 10),
                  child: Text(
                    '*',
                    style: ytTextStyle(
                        color: Colour.warningTextColor,
                        fontWeight: FontWeight.w500),
                  ),
                )
              : Gaps.hGap16,
          Text(
            ResKey.mineUserManagerUserAvatar.tr,
            style: ytTextStyle(
                fontSize: 16,
                fontWeight: FontWeight.normal,
                color: Colour.mainTextColor),
          ),
          const Spacer(),
          MyGestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if (isCanClick) {
                _askUserForImageSource();
              }
            },
            child: Container(
              padding:
                  EdgeInsets.only(left: 6, right: isShowRightArrow ? 0 : 16),
              child: ClipOval(
                child: LoadImage(
                  avatarUrl,
                  holderImg: holderImg,
                  width: 44,
                  height: 44,
                ),
              ),
            ),
          ),
          Visibility(
              visible: isShowRightArrow,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  _askUserForImageSource();
                },
                child: Container(
                  padding: const EdgeInsets.only(left: 6, right: 16),
                  child: Image.asset(
                    'assets/images/right_arrow.png',
                    width: 16.w,
                    height: 16.w,
                  ),
                ),
              ))
        ],
      ),
    );
  }

  Future<ImageSource?> _askUserForImageSource() async {
    return await showCupertinoModalPopup(
      context: Get.context!,
      builder: (BuildContext context) => CupertinoActionSheet(
        cancelButton: CupertinoActionSheetAction(
          isDestructiveAction: true,
          child: Text(
            ResKey.cancel.tr,
            style: const TextStyle(color: Colour.primaryColor),
          ),
          onPressed: () {
            Navigator.pop(context, null);
          },
        ),
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: Text(
              ResKey.camera.tr,
              style: const TextStyle(color: Colour.warningTextColor),
            ),
            onPressed: () {
              _handleImage(context, ImageSource.camera);
            },
          ),
          CupertinoActionSheetAction(
            child: Text(ResKey.gallery.tr),
            onPressed: () async {
              _handleImage(context, ImageSource.gallery);
            },
          ),
        ],
      ),
    );
  }

  _handleImage(BuildContext context, ImageSource source) async {
    Navigator.pop(context, source);
    final ImagePicker imagePicker = ImagePicker();
    final image = await imagePicker.pickImage(source: source, imageQuality: 50);
    if (image == null) {
      return;
    }
    var cropSettings = const ImageManipulationSettings(
        enableCropping: true, compressQuality: 50);
    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: image.path,
      maxWidth: cropSettings.maxWidth,
      maxHeight: cropSettings.maxHeight,
      uiSettings: [
        IOSUiSettings(
            doneButtonTitle: ResKey.confirm.tr,
            cancelButtonTitle: ResKey.cancel.tr),
        AndroidUiSettings(
            toolbarTitle: '', hideBottomControls: true), //没办法 ，只能干掉工具栏支持国际化版本
      ],
    );
    var file = File(croppedFile!.path);
    uploadImage(file);
  }

  ///上传单张图片
  void uploadImage(File? image) async {
    if (image != null) {
      showLoading(toast: ResKey.loading.tr);
      var result = await CommonServices().upload(image);
      dismissLoading();
      if (result != null && result['url'] != null) {
        imageUrlCallBack(result['url'].toString());
      }
    }
  }
}
